//
//  AppDelegate.swift
//  ShouChong
//
//  Created by 陈友文 on 2024/6/11.
//

import UIKit
import MMDrawerController
import AppTrackingTransparency
import GoogleMobileAds
import RevenueCat

@main
class AppDelegate: UIResponder, UIApplicationDelegate {
    
    var window: UIWindow?
    var appOpenAd:GADAppOpenAd!
    var loadTime:Date?
    var userVM:UserViewModel = UserViewModel(getNow: false)
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        
        self.window = UIWindow.init(frame: kScreenBounds)
        if let token = UserDefaults.standard.value(forKey: "login_token") as? String {
            if token.isEmpty {
                firstView()
            } else {
                goToHome()
            }
        } else {
            firstView()
        }
        self.setupRevenueCat()
        DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
            
            self.checkPurchase()
        }
        return true
    }
    func applicationDidBecomeActive(_ application: UIApplication) {
        if #available(iOS 14, *) {
            ATTrackingManager.requestTrackingAuthorization { status in
                print(status)
                if let isVip = UserDefaults.standard.value(forKey: kVipKey) as? Bool {
                    if !isVip {
                        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.0) {
                            AppOpenAdManager.shared.showAdIfAvailable()
                        }
                    }
                } else {
                    UserDefaults.standard.setValue(false, forKey: kVipKey)
                    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.0) {
                        AppOpenAdManager.shared.showAdIfAvailable()
                    }
                }
            }
        } else {
            // Fallback on earlier versions
        }
    }
    
    func goToHome() {
        let vc = BaseNavController(rootViewController: HomeViewController())
        let settingVC = OpenNavViewController(rootViewController: SettingViewController())
        let mmVC = MMDrawerController(center: vc, leftDrawerViewController:settingVC)
        mmVC?.openDrawerGestureModeMask = .all
        mmVC?.closeDrawerGestureModeMask = .all
        mmVC?.showsShadow = true
        mmVC?.maximumLeftDrawerWidth = 200
        mmVC?.shadowRadius = 5
        mmVC?.shadowColor = .gray.withAlphaComponent(0.4)
        mmVC?.shouldStretchDrawer = false
        self.window?.makeKeyAndVisible()
        self.window?.rootViewController = mmVC
    }
    
    func firstView() {
        let vc = OpenNavViewController(rootViewController: WelcomeViewController())
        self.window?.makeKeyAndVisible()
        self.window?.rootViewController = vc
    }
    

}

extension AppDelegate {
    /// 订阅相关
    
    func setupRevenueCat() {
                Purchases.logLevel = .debug
                Purchases.configure(withAPIKey: "appl_sjWpjVcmJGNnKxmtSJUwYUaKNAW")
    }
    
    func checkPurchase() {
        Purchases.shared.getCustomerInfo { customInfo, err in
            guard let customInfo = customInfo, err == nil else {
                UserDefaults.standard.set(false, forKey: kVipKey)
//                YWProgressHUD.showTextHudTips(message: "获取订阅信息失败")
                self.userVM.setUserInfoVIP(isVIp: false)
                return
            }
            if customInfo.entitlements[kPurchaseName]?.isActive == true {
                UserDefaults.standard.set(true, forKey: kVipKey)
                self.userVM.setUserInfoVIP(isVIp: true)
            } else {
                UserDefaults.standard.set(false, forKey: kVipKey)
                self.userVM.setUserInfoVIP(isVIp: false)
            }
        }
    }
}

extension UIApplication {
    func endEditing() {
        sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
    }
}


